package com.itheima.utils;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class HeiMaUtils {
    private static Whitelist whitelist = new Whitelist();;
    static {
        whitelist.addTags("a", "br", "span");
        whitelist.addAttributes("img", "src");
        whitelist.addAttributes("font", "color", "size");
        whitelist.addAttributes(":all", "style");

        // HtmlUtils.htmlEscape();
        // JavaScriptUtils.javaScriptEscape();
    }

    public static String htmlWhiteList(String html) {
        String clean = Jsoup.clean(html, whitelist);
        return clean;
    }

    public static String htmlEscape(String html) {
        return html
                .replaceAll("<", "&lt;") // 处理HTML主体内容注入
                .replaceAll(">", "&gt;") // 处理HTML主体内容注入
                .replaceAll("\"", "&quot;") // 处理属性注入,属性值使用""时
                .replaceAll("'", "&#39;"); // 处理属性注入,属性值使用''时
    }

    public static String htmlJS(String js) {
        return js
                .replaceAll("\\\\", "\\\\\\\\")             // \\\\
                .replaceAll("\"", "\\\\\"")                 // \\"
                .replaceAll("\'", "\\\\\'");                // \\'
    }

    public static void sendLoginSameSiteCookie(HttpSession session, HttpServletResponse response) {
        ResponseCookie cookie = ResponseCookie.from("JSESSIONID", session.getId()) // key & value
                .httpOnly(true)		// 禁止js读取
                .secure(false)		// 在http下也传输
                .domain("localhost")// 域名
                .path("/")			// path
                .sameSite("Strict")	// Cookies只会在第一方上下文中发送，不会与第三方网站发起的请求一起发送。
                .build();

        // 设置Cookie Header
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
    }
}
